﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace RobotsFight.RobotImplementation
{
    public class Array2DCoordinateStorage : CoordinateStorage
    {
        private bool [,] _storage;

        public Array2DCoordinateStorage(int maxX, int maxY)
        {
            _storage = new bool[maxX, maxY];
        } 

        public override void   AddCordinate(int x, int y)
        {
            _storage[x, y] = true;
        } 
       
        public override bool   HasBeenAtCoordinate(int x, int y)
        {
            x = Math.Max(x, 0) & Math.Min(x, Console.BufferWidth - 1);
            y = Math.Max(y, 0) & Math.Min(y, Console.BufferHeight - 1);
            return _storage[x, y];
        }

        public override bool IsRobotBlocked(int x, int y, bool isRigtMost, bool isBottomMost)
        {            
            bool isLeftFree;

            if (x == 0)
                isLeftFree = false;
            else
                isLeftFree = !HasBeenAtCoordinate(x - 1, y);

            bool isTopFree;

            if (y == 0)
                isTopFree = false;
            else
                isTopFree = !HasBeenAtCoordinate(x, y - 1);

            bool isBottomFree;

            if (isBottomMost)
                isBottomFree = false;
            else
                isBottomFree = !HasBeenAtCoordinate(x, y + 1);


            bool isRightFree;

            if (isRigtMost)
                isRightFree = false;
            else
                isRightFree = !HasBeenAtCoordinate(x + 1, y);

            return !(isLeftFree || isTopFree || isBottomFree || isRightFree);
        }

        public override void   FreeRobot(int x, int y, Direction d)
        {
            switch (d)
            {
                case Direction.Top:
                    RemoveCoordinate (x, y - 1);
                    break;
                case Direction.Left:
                    RemoveCoordinate(x - 1,y);
                    break;
                case Direction.Bottom:
                    RemoveCoordinate(x,y + 1);
                    break;
                case Direction.Right:
                    RemoveCoordinate(x + 1,y);
                    break;
                default:
                    break;
            }
        }

        public void RemoveCoordinate(int x, int y)
        {
            _storage[x, y] = false;
        }
    }
}
